const canvas = document.getElementById("board");
const ctx = canvas.getContext("2d");
const statusDiv = document.getElementById("status");
const restartButton = document.getElementById("restartButton");
const boardSize = 15;
const cellSize = canvas.width / boardSize;
let board;
let currentPlayer;
let gameOver;

function initializeGame() {
  board = Array.from({ length: boardSize }, () => Array(boardSize).fill(null));
  currentPlayer = "black";
  gameOver = false;
  statusDiv.textContent = "轮到玩家黑棋";
  restartButton.style.display = "none";
  drawBoard();
}

function drawBoard() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  for (let i = 0; i <= boardSize; i++) {
    ctx.beginPath();
    ctx.moveTo(i * cellSize, 0);
    ctx.lineTo(i * cellSize, canvas.height);
    ctx.stroke();

    ctx.beginPath();
    ctx.moveTo(0, i * cellSize);
    ctx.lineTo(canvas.width, i * cellSize);
    ctx.stroke();
  }
}

function placePiece(x, y, color) {
  ctx.beginPath();
  ctx.arc(
    x * cellSize + cellSize / 2,
    y * cellSize + cellSize / 2,
    cellSize / 3,
    0,
    2 * Math.PI
  );
  ctx.fillStyle = color;
  ctx.fill();
}

function checkWin(x, y) {
  const directions = [
    { dx: 1, dy: 0 },
    { dx: 0, dy: 1 },
    { dx: 1, dy: 1 },
    { dx: 1, dy: -1 },
  ];

  function countInDirection(dx, dy) {
    let count = 0;
    for (let step = 1; step < 5; step++) {
      const nx = x + step * dx;
      const ny = y + step * dy;
      if (
        nx >= 0 &&
        ny >= 0 &&
        nx < boardSize &&
        ny < boardSize &&
        board[nx][ny] === currentPlayer
      ) {
        count++;
      } else {
        break;
      }
    }
    return count;
  }

  for (const { dx, dy } of directions) {
    const count = 1 + countInDirection(dx, dy) + countInDirection(-dx, -dy);
    if (count >= 5) {
      return true;
    }
  }

  return false;
}

function restartGame() {
  initializeGame();
}

canvas.addEventListener("click", (event) => {
  if (gameOver) {
    return;
  }

  const rect = canvas.getBoundingClientRect();
  const x = Math.floor((event.clientX - rect.left) / cellSize);
  const y = Math.floor((event.clientY - rect.top) / cellSize);

  if (board[x][y] !== null) {
    return;
  }

  board[x][y] = currentPlayer;
  placePiece(x, y, currentPlayer);

  if (checkWin(x, y)) {
    statusDiv.textContent =
      "玩家" + (currentPlayer === "black" ? "黑棋" : "白棋") + "获胜！";
    gameOver = true;
    restartButton.style.display = "block";
    return;
  }

  currentPlayer = currentPlayer === "black" ? "white" : "black";
  statusDiv.textContent =
    "轮到玩家" + (currentPlayer === "black" ? "黑棋" : "白棋");
});

initializeGame();
